package com.main.sales.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.main.sales.common.R;
import com.main.sales.dto.SetmealDto;
import com.main.sales.pojo.Category;
import com.main.sales.pojo.Setmeal;
import com.main.sales.pojo.SetmealDish;
import com.main.sales.service.CategoryService;
import com.main.sales.service.SetmealDishService;
import com.main.sales.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
//    @Autowired
//    private RedisTemplate redisTemplate;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    @ApiOperation(value = "新增套餐")
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息：{}", setmealDto.toString());
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    // http://localhost:8080/setmeal/page?page=1&pageSize=10
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R<Page<SetmealDto>> getPage(int page, int pageSize, String name) {
        log.info("套餐名称:{}", name);
        //1.
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        //2.
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(name), Setmeal::getName, name);
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //3.
        setmealService.page(pageInfo, lqw);

        //1、
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);
        //2、
        BeanUtils.copyProperties(pageInfo, setmealDtoPage, "records");
        //3、
        List<Setmeal> records = pageInfo.getRecords();
        //4、
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        //5、
        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }

    /**
     * 根据id删除套餐,同时删除套餐和菜品关联关系
     *
     * @param ids
     * @return
     */
    //http://localhost:8080/setmeal?ids=1555484938470461441
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    @ApiOperation(value = "根据id删除套餐,同时删除套餐和菜品关联关系")
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("根据id删除套餐,同时删除套餐和菜品关联关系{}", String.valueOf(ids));
        setmealService.deleteWithDish(ids);
        return R.success("删除成功");
    }

    /**
     * 根据id修改套餐状态
     *
     * @param id
     * @param ids
     * @return
     */
    //http://localhost:8080/setmeal/status/0?ids=1415580119015145474
    @PostMapping("/status/{id}")
    @ApiOperation(value = "根据id修改套餐状态")
    public R<String> update(@PathVariable int id, String ids) {
        log.info("根据id修改套餐状态：{}==={}", id, ids);
        String[] split = ids.split(",");
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(id);
        for (String s : split) {
            setmeal.setId(Long.parseLong(s));
            setmealService.updateById(setmeal);
        }
        return R.success("修改成功");
    }

    /**
     * 用户界面套餐回显
     *
     * @param setmeal
     * @return
     */
    //    http://localhost:8080/setmeal/list?categoryId=1413386191767674881&status=1
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId+'_'+#setmeal.status")
    @ApiOperation(value = "用户界面套餐回显")
    public R<List<Setmeal>> list(Setmeal setmeal) {
//        List<Setmeal> setmealList = null;
//        String key = "setmeal_" + setmeal.getCategoryId() + "_" + setmeal.getStatus();
        //1、先从Redis中 获取缓存数据
//        setmealList = (List<Setmeal>) redisTemplate.opsForValue().get(key);
        //2、若果存在直接返回无需查询数据库
//        if (setmealList != null) {
//            return R.success(setmealList);
//        }

        log.info("用户界面套餐回显：{}", setmeal.toString());
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = setmealService.list(lqw);//套餐信息
        //3、若果不存在，需要查询数据库，将数据缓存到Redis中
//        redisTemplate.opsForValue().set(key, setmealList, 60, TimeUnit.MINUTES);
        return R.success(setmealList);
    }

    /**
     * 修改界面，回显数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "修改界面，回显数据")
    public R<SetmealDto> list(@PathVariable Long id) {
        SetmealDto setmealDto = new SetmealDto();
        //套餐基础信息
        Setmeal byId = setmealService.getById(id);
//        log.info("修改界面,套餐基础信息{}",byId);
        //拷贝基础数据
        BeanUtils.copyProperties(byId, setmealDto);
        //菜品信息
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(lqw);
        setmealDto.setSetmealDishes(list);
//        log.info("修改界面{}",list);
        return R.success(setmealDto);

    }

    /**
     * 修改套餐信息
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    @ApiOperation(value = "修改套餐信息")
    public R<String> addsave(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息：{}", setmealDto.toString());
        setmealService.updateById(setmealDto);
//        String key = "setmeal_*" + setmealDto.getCategoryId() + "_1";
//        Set keys = redisTemplate.keys(key);
//        redisTemplate.delete(keys);
        return R.success("套餐已更新");
    }
}
